package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.client.ArticleFeign;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.AuthorDto;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.dtos.UserAuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserAuth;
import com.heima.user.mapper.ApUserAuthMapper;
import com.heima.user.service.ApUserAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.ApUserService;
import com.heima.wemedia.client.WemediaFeign;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import sun.util.resources.et.CalendarData_et;

import java.util.Date;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2021-11-24
 */
@Slf4j
@Service
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements ApUserAuthService {

    /**
     * 分页查询认证信息
     * @param dto
     * @return
     */
    @Override
    public PageResult<UserAuthDto> findByPage(AuthDto dto) {
//        设置分页条件
        IPage<ApUserAuth> ipage = new Page<>(dto.getPage(),dto.getSize());
//        设置查询条件
        QueryWrapper<ApUserAuth> queryWrapper = new QueryWrapper<>();
        if(dto.getStatus() != null){
            queryWrapper.lambda().eq(ApUserAuth::getStatus,dto.getStatus());
        }
//        分页查询
        IPage<ApUserAuth> userAuthIPage = page(ipage, queryWrapper);
        if (userAuthIPage == null || CollectionUtils.isEmpty(userAuthIPage.getRecords())) {
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        构造返回对象
        return new PageResult<>(dto.getPage(),
                dto.getSize(),
                userAuthIPage.getTotal(),
                BeanHelper.copyWithCollection(userAuthIPage.getRecords(),UserAuthDto.class));
    }

    @Autowired
    private ApUserService apUserService;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    /**
     * 用户认证
     * @param dto
     * @param status
     */
    @Override
    //@Transactional  //本地事务
    @GlobalTransactional
    public void userAuth(AuthDto dto, int status) {

//        根据apUserAuth的主键id，修改status
        ApUserAuth apUserAuth = new ApUserAuth();
        apUserAuth.setId(dto.getId());
        apUserAuth.setStatus(status);
        apUserAuth.setUpdatedTime(new Date());
        if(status==2){
            apUserAuth.setReason(dto.getMsg());
        }
        boolean b = updateById(apUserAuth);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        if(status==2){
//            如果审核状态为不通过，直接返回
            return ;
        }
//        根据ApUserAuth的主键id 查询及记录
        apUserAuth = getById(dto.getId());
        Integer apUserId = apUserAuth.getUserId();
//        查询apuuser的数据
        ApUser apUser = apUserService.getById(apUserId);
//        用Feign远程调用自媒体服务，创建自媒体用户
        WmUserDto wmUserDto = new WmUserDto();
        wmUserDto.setApUserId(apUserId);
        wmUserDto.setName(apUser.getName());
        wmUserDto.setPhone(apUser.getPhone());
        wmUserDto.setPassword(apUser.getPassword());
        wmUserDto.setImage(apUser.getImage());
        wmUserDto.setStatus(9);
        try{
            Integer wmUserId = wemediaFeign.save123(wmUserDto);
            wmUserDto.setId(wmUserId);
        }catch(Exception e){
            log.error("远程调用自媒体服务 异常！");
            e.printStackTrace();
        }

//        用Feign远程调用article服务，创建作者用户
        AuthorDto authorDto = new AuthorDto();
        authorDto.setWmUserId(wmUserDto.getId());
        authorDto.setUserId(apUserId);
        authorDto.setName(apUser.getName());
        authorDto.setType(2);
        try {
            Integer authorId = articleFeign.saveAuthor(authorDto);
        }catch (Exception e){
            log.error("远程调用article服务 异常！");
            e.printStackTrace();
        }
//        测试全局事务
//        System.out.println(1/0);
//        修改apUser表的flag字段，改为1-自媒体人
        apUser = new ApUser();
        apUser.setId(apUserId);
        apUser.setFlag(1);
        boolean b1 = apUserService.updateById(apUser);
        if(!b1){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
